
class BankAccount {
    public static void main(String[] args) {
        // 创建银行账户对象
        BankAccount account = new BankAccount();
        // 创建存款者和取款者对象
        Depositor depositor = new Depositor(account);
        Withdrawer withdrawer = new Withdrawer(account);
        // 创建两个线程
        Thread t1 = new Thread(depositor, "存款者线程");
        Thread t2 = new Thread(withdrawer, "取款者线程");
        // 启动线程
        t1.start();
        t2.start();
    }

    private int balance;
    private boolean flag = false;

    // 存款
    public synchronized void deposit(int amount) {
        // 如果有余额，等待取款者取走余额
        if (flag) {
            try {
                wait();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
        this.balance = amount;
        System.out.println("存款者存入：" + this.balance);
        flag = true;
        notifyAll();
    }

    // 取款
    public synchronized void withdraw() {
        // 如果没有余额，等待存款者存入余额
        if (!flag) {
            try {
                wait();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
        System.out.println("取款者取出：" + this.balance);
        flag = false;
        notifyAll();
    }
}

class Depositor implements Runnable {
    private BankAccount account;

    public Depositor(BankAccount account) {
        this.account = account;
    }

    @Override
    public void run() {
        for (int i = 1; i < 11; i++) {
            account.deposit(i * 100);
        }
    }
}

class Withdrawer implements Runnable {
    private BankAccount account;

    public Withdrawer(BankAccount account) {
        this.account = account;
    }

    @Override
    public void run() {
        while (true) {
            account.withdraw();
        }
    }
}